package scaladuct.l10n

import scaladuct.Property
import java.util.{MissingResourceException, ResourceBundle, Locale}
import java.net.URL
import java.lang.String

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Dec 13, 2010
 * Time: 12:33:30 PM
 */

@serializable @SerialVersionUID(1L)
trait ResourceBundleHasHintsMetaDataSource extends HasHintsMetaDataSource with L10nProperties {
  val pageNameInBundle: String

  def configPageMetaData(locale: Locale) = {
    bundle(locale) match {
      case Some(bndl) =>
        Some(new ResourceBundleHasHintsMetaData(bndl, pageNameInBundle))
      case None => None
    }

  }

}

class ResourceBundleHasHintsMetaData(resourceBundle: ResourceBundle,
                                     pageName: String) extends HasHintsMetaData {
  val pagePrefix = if (pageName == null || pageName == "") "" else pageName + '.'
  val pageLocale: Locale = resourceBundle.getLocale
  val pageMeta = Some(new ResourceBundleCommonMetaData(resourceBundle, pagePrefix))

  def propertyMeta[X](property: Property[X]) = {
    Some(new ResourceBundleCommonMetaData(resourceBundle,
      pagePrefix + property.name + '.'))
  }

  def propertyValueMeta[X](property: Property[X]) = {
    Some(new ResourceBundleCommonMetaData(resourceBundle,
      pagePrefix + property.name + '.' + property.value + '.'))
  }

  def hintMeta[H](hint: Property[H]): Option[CommonMetaData] = {
    Some(new ResourceBundleCommonMetaData(resourceBundle,
      pagePrefix+ "hint." + hint.name + '.'))
  }
}

class ResourceBundleCommonMetaData(resourceBundle: ResourceBundle,
                                   prefix: String) extends CommonMetaData {
  lazy val icon = getUrlFromBundle("icon")
  lazy val description = getStringFromBundle("description")
  lazy val title = getStringFromBundle("title")

  private def getStringFromBundle(key: String): Option[String] = {
    try {
      val value: String = resourceBundle.getString(prefix + key)
      Some(value)
    }
    catch {
      case mre: MissingResourceException => None
    }
  }

  private def getUrlFromBundle(key: String): Option[URL] = {
    getStringFromBundle(key) match {
      case Some(urlAsString) => Some(new URL(urlAsString))
      case None => None
    }
  }

}